package com.cms.controller.front;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;

import com.cms.Feedback;
import com.cms.entity.Cart;
import com.cms.entity.CartItem;
import com.cms.entity.Member;
import com.cms.entity.Order;
import com.cms.entity.OrderItem;
import com.cms.entity.Product;
import com.cms.entity.Receiver;
import com.cms.routes.RouteMapping;


/**
 * Controller - 订单
 * 
 * 
 * 
 */
@RouteMapping(url = "/order")
public class OrderController extends BaseController{

	
	/**
	 * 添加
	 */
	public void add(){
	    Long productId = getParaToLong("productId");
	    Integer quantity = getParaToInt("quantity");
		Order.Type orderType = getParaToEnum(Order.Type.class,"orderType");
		Member currentMember = getCurrentMember();
		Member member = new Member().dao().findById(getCurrentMember().getId());
		setAttr("member",member);
		Receiver receiver = new Receiver().dao().findDefault(currentMember.getId());
		if(productId!=null){
			//单商品下订单
			Product product = new Product().dao().findById(productId);
			setAttr("product", product);
			setAttr("quantity", quantity);
			setAttr("productId", productId);
			//商品总额
			BigDecimal productPrice = product.getRealPrice().multiply(new BigDecimal(quantity));
			setAttr("productPrice", productPrice);
			//运费总额
			BigDecimal freightPrice = BigDecimal.ZERO;
			setAttr("freightPrice", freightPrice);
			//订单总额
			BigDecimal orderPrice = productPrice.add(freightPrice);
			setAttr("orderPrice", orderPrice);
			setAttr("orderType", orderType.name());
			setAttr("receiver",receiver);
			render("/templates/"+getTheme()+"/"+getDevice()+"/order_add.html");
		}else{
			//购物车下订单
			Cart currentCart = getCurrentCart();
			setAttr("currentCart",currentCart);
			//商品总额
			setAttr("productPrice", currentCart.getTotalPrice());
			//运费总额
			BigDecimal freightPrice = BigDecimal.ZERO;
			setAttr("freightPrice", freightPrice);
			//订单总额
			BigDecimal orderPrice = currentCart.getTotalPrice().add(freightPrice);
			setAttr("orderPrice", orderPrice);
			setAttr("orderType", Order.Type.CART_BUY.name());
			setAttr("receiver",receiver);
			render("/templates/"+getTheme()+"/"+getDevice()+"/order_add.html");
		}
	}
	
	/**
	 * 保存
	 */
	public void save(){
	    Order order = getModel(Order.class,"",true);
	    Order.Type orderType = getParaToEnum(Order.Type.class,"orderType");
	    order.setType(orderType.ordinal());
	    //收货地址数据
	    Receiver receiver = new Receiver().dao().findById(getParaToLong("receiverId"));
	    order.setProvince(receiver.getProvince());
	    order.setCity(receiver.getCity());
	    order.setDistrict(receiver.getDistrict());
	    order.setAddress(receiver.getAddress());
	    order.setConsignee(receiver.getConsignee());
	    order.setPhone(receiver.getPhone());
	    order.setExpireDate(DateUtils.addHours(new Date(), 2));
	    
		Member currentMember = getCurrentMember();
		if(order.getType() == Order.Type.CART_BUY.ordinal()){
			//订单信息
			Cart currentCart = getCurrentCart();
			order.setCreateDate(new Date());
			order.setModifyDate(new Date());
			order.setAmount(currentCart.getTotalPrice());
			order.setSn(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS")+RandomStringUtils.randomNumeric(5));
			order.setStatus(Order.Status.PENDING_PAYMENT.ordinal());
			order.setMemberId(currentMember.getId());
			order.save();
			List<CartItem>  cartItems = currentCart.getCartItems();
			for(CartItem cartItem:cartItems){
				//订单项信息
				OrderItem orderItem = new OrderItem();
				orderItem.setCreateDate(new Date());
				orderItem.setModifyDate(new Date());
				orderItem.setName(cartItem.getProduct().getName());
				orderItem.setPrice(cartItem.getPrice());
				orderItem.setQuantity(cartItem.getQuantity());
				orderItem.setSn(cartItem.getProduct().getSn());
				orderItem.setImage(cartItem.getProduct().getImage());
				orderItem.setOrderId(order.getId());
				orderItem.setProductId(cartItem.getProductId());
				orderItem.save();
			}
			//清除购物车
			for(CartItem cartItem:cartItems){
				new CartItem().dao().deleteById(cartItem.getId());
			}
		}else{
			Long productId = getParaToLong("productId");
		    Integer quantity = getParaToInt("quantity");
		    Product product = new Product().dao().findById(productId);
		    BigDecimal subtotal = product.getRealPrice().multiply(new BigDecimal(quantity));
		    //订单信息
			order.setCreateDate(new Date());
			order.setModifyDate(new Date());
			order.setAmount(subtotal);
			order.setSn(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS")+RandomStringUtils.randomNumeric(5));
			order.setStatus(Order.Status.PENDING_PAYMENT.ordinal());
			order.setMemberId(currentMember.getId());
			order.save();
			//订单项信息
			OrderItem orderItem = new OrderItem();
			orderItem.setCreateDate(new Date());
			orderItem.setModifyDate(new Date());
			orderItem.setName(product.getName());
			orderItem.setPrice(product.getRealPrice());
			orderItem.setQuantity(quantity);
			orderItem.setSn(product.getSn());
			orderItem.setImage(product.getImage());
			orderItem.setOrderId(order.getId());
			orderItem.setProductId(productId);
			orderItem.save();
		}
		Map<String,Object> result = new HashMap<>();
		result.put("orderId", order.getId());
		result.put("orderSn", order.getSn());
		renderJson(Feedback.success(result));
	}
	
	/**
	 * 删除
	 */
	public void delete(){
		Long orderId = getParaToLong("orderId");
		Order order = new Order().dao().findById(orderId);
		order.setStatus(Order.Status.CLOSED.ordinal());
		order.update();
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	/**
	 * 取消
	 */
	public void cancel(){
		Long orderId = getParaToLong("orderId");
		Order order = new Order().dao().findById(orderId);
		order.setStatus(Order.Status.CANCELED.ordinal());
		order.update();
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	/**
	 * 已完成
	 */
	public void complete(){
		Long orderId = getParaToLong("orderId");
		Order order = new Order().dao().findById(orderId);
		order.setStatus(Order.Status.COMPLETED.ordinal());
		order.update();
		renderJson(Feedback.success(new HashMap<>()));
	}
	
	/**
	 * 支付
	 */
	public void payment(){
		Long orderId = getParaToLong("orderId");
		Order order = new Order().dao().findById(orderId);
		Member member = new Member().dao().findById(getCurrentMember().getId());
		setAttr("order",order);
		setAttr("member",member);
		render("/templates/"+getTheme()+"/"+getDevice()+"/order_payment.html");
	}
}
